package com.ler.yrmall.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.apache.dubbo.rpc.service.GenericService;

import java.util.concurrent.CompletableFuture;

/**
 * @author leron
 */
@Slf4j
@Activate(group = CommonConstants.PROVIDER)
public class RpcCallExceptionFilter implements Filter {

    public Result invoke(Invoker<?> invoker, Invocation invocation) {
        Result result = null;
        try {
            result = invoker.invoke(invocation);
            if (result.hasException() && GenericService.class != invoker.getInterface()) {
                Throwable exception = result.getException();
                log.error("调用失败:",exception);
                com.ler.yrmall.basic.Result<?> response = com.ler.yrmall.basic.Result.error(exception.getMessage());
                return new AsyncRpcResult(CompletableFuture.supplyAsync(() -> new AppResponse(response)),invocation);
            }
        } catch (RuntimeException e) {
            log.error("全局异常处理失败", e);
        }
        return result;
    }
}